const { descrypt_fields_sm4 } = require('../../util/crypt')
const { DecryptErr } = require('../../response/code')
// 密码解密
function passwdDecryptSm4(ctx, next) {
  const { passwd, newPasswd } = ctx.request.body
  const sm4Key = process.env.SM4_KEY
  console.log(passwd, newPasswd, '<<<< update')
  let decodeFields = []
  if (passwd) {
    decodeFields.push('passwd')
  }
  if (newPasswd) {
    decodeFields.push('newPasswd')
  }

  if (decodeFields.length === 0) {
    return next()
  }
  const body = descrypt_fields_sm4(ctx.request.body, sm4Key, decodeFields)
  // 对需要解密的字段解密
  // body = descrypt_fields_sm4(ctx.request.body, sm4Key, ['passwd', 'newPasswd'])
  if (passwd && body['passwd'] == '') {
    return ctx.app.emit('error', DecryptErr, ctx)
  }
  if (newPasswd && body['newPasswd'] == '') {
    return ctx.app.emit('error', DecryptErr, ctx)
  }
  return next()
}

module.exports = {
  passwdDecryptSm4,
}
